import PageParam from '@main/bo/PageParam'
import { ArgumentMetadata, PipeTransform } from '@nestjs/common'

export class QueryPageParamPipe
  implements PipeTransform<Record<'size' | 'current', string | string[] | undefined>, PageParam>
{
  transform(value: Record<'size' | 'current', string | string[]>, metadata: ArgumentMetadata): PageParam {
    console.log('metadata', metadata)
    console.log('value', value)
    let size = 15
    let current = 1
    if (metadata.type === 'query') {
      size = toInt(15, value.size)
      current = toInt(1, value.current)
    }
    return PageParam.builder(current, size)
  }
}

function toInt(defaultVal: number, val?: string | string[]) {
  if (val && !Array.isArray(val)) {
    try {
      return parseInt(val)
    } catch (e) {
      console.log('分页参数转换异常:', val)
    }
  }
  return defaultVal
}
